package com.macro.cloud.gitee.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.macro.cloud.gitee.config.Oauth2Config;
import com.macro.cloud.gitee.domain.AccessTokenDto;
import com.macro.cloud.gitee.domain.GiteeClientUserDto;
import com.macro.cloud.gitee.domain.Oauth2ClientUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class Oauth2ClientService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private Oauth2Config oauth2Config;

    public Oauth2ClientService(Oauth2Config oauth2Config) {
        this.oauth2Config = oauth2Config;
        logger.info("oauth2 config info:");
        logger.info("getOauth2Server:{}",oauth2Config.getOauth2Server());
        logger.info("getClientId:{}",oauth2Config.getClientId());
        logger.info("getClientSecret:{}",oauth2Config.getClientSecret());
        logger.info("getOauth2CodeUrl:{}",oauth2Config.getOauth2CodeUrl());
    }

    /**
     * 获取授权码链接
     * @return
     */
    public String getOauth2CodeUrl() {
        return oauth2Config.getOauth2CodeUrl();
    }

    /**
     * 根据授权码获取token信息
     * @param code
     * @return
     */
    public String getAccessToken(String code){
        Map<String,Object> map=new HashMap<>();
        map.put("client_id",oauth2Config.getClientId());
        map.put("redirect_uri",oauth2Config.getRedirectUri());
        map.put("code",code);
        map.put("client_secret",oauth2Config.getClientSecret());
        map.put("grant_type","authorization_code");
        //授权方式无效，或者登录回调地址无效、过期或已被撤销
        String jsonData = HttpUtil.post(oauth2Config.getOauth2TokenApi(), map);
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        String token = (String)jsonObject.get("access_token");
        return token;
    }

    /**
     * 获取登录用户信息
     * @param accessToken
     * @return Oauth2ClientUserDto
     */
    public GiteeClientUserDto getCurrentUser(String accessToken){
        String loginUserJson = HttpRequest.get(oauth2Config.getOauth2CurrentUserApi())
                .form("access_token",accessToken)
                .execute().body();
        GiteeClientUserDto oauth2ClientUserDto = JSON.parseObject(loginUserJson, GiteeClientUserDto.class);
        return oauth2ClientUserDto;

    }




}
